package com.lcsolute.admin.utils;

import java.sql.Date;
import java.util.Base64;
import java.util.UUID;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * JWT 工具类
 */
public class JwtUtil {
    // 有效期 60 * 60 * 1000 = 1 hour
    public static final Long JWT_TTL = 60 * 60 * 1000L;

    // 设置密钥明文
    public static final String JWT_KEY = "lcsolute";

    public static String getUUID() {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    /**
     * 生成 jwt
     * @param subject token 中存放数据（json格式）
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, JwtUtil.getUUID());
        return builder.compact();
    }

    /**
     * 生成 jwt
     * @param subject token 中要存放的数据（json 格式）
     * @param ttlMillis token 超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, JwtUtil.getUUID());
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null) {
            ttlMillis = JwtUtil.JWT_TTL;
        }
        long expMillis = ttlMillis +nowMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid) // 唯一 id
                .setSubject(subject) // 主题 可以是 JSON 数据
                .setIssuer("lcsolute") // 签发着
                .setIssuedAt(now) // 签发时间
                .signWith(signatureAlgorithm, secretKey) // 使用 HS256 对称加密算法签名，第二个参数为 密钥
                .setExpiration(expDate);
    }
    
    /**
     * 创建 token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        return  builder.compact();
    }

    public static void main(String[] args) throws Exception{
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), "subject", null);
        System.out.println(token);
        Claims claims = JwtUtil.parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJmYmZlZGYzNjk2ZmI0OTZiODFkZWVhYWQ3NDFmOTY5OSIsInN1YiI6IjIiLCJpc3MiOiJsY3NvbHV0ZSIsImlhdCI6MTY0NTA5ODk0NiwiZXhwIjoxNjQ1MTAyNTQ2fQ.-loUYxerHjSwAKWlUIr66zU_an5Tw9QABDVClJREQCk");
        System.out.println(claims);
    }

    /**
     * 生成加密后的密钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析
     * 
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

}